<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets" style="margin-top: 5px"></i>
      <span style="margin-top: 5px">数据列表</span>

      <el-button
        class="btn-add"
        @click="handleAddProductCate()"
        size="mini">
        添加
      </el-button>
      <el-button
        class="btn-add"
        v-show="!(parentId===0)"
        @click="$router.go(-1)"
        size="mini">
        返回上级
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="productCateTable"
                style="width: 100%"
                :data="list"
                v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="分类名称" width="200" align="center">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="分类描述" align="center">
          <template slot-scope="scope">{{ scope.row.description }}</template>
        </el-table-column>
        <el-table-column label="是否启用" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.hidden">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="级别" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.level | levelFilter }}</template>
        </el-table-column>
        <el-table-column label="商品数量" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.productCount }}</template>
        </el-table-column>
        <el-table-column label="排序" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="设置" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :disabled="scope.row.children.length === 0"
              @click="handleShowNextLevel(scope.$index, scope.row)">查看下级
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleUpdate(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        @close="closeHandler"
        @open="getTopCateList"
        :title="isEdit?'编辑分类':'添加分类'"
        :visible.sync="dialogVisible"
        width="40%">
        <el-form :model="productCate"
                 :rules="rules"
                 ref="adminForm"
                 label-width="150px" size="small">
          <el-form-item label="分类名称：" prop="name">
            <el-input v-model="productCate.name"></el-input>
          </el-form-item>
          <el-form-item label="上级分类：" prop="parentId">
            <el-select v-model="productCate.parentId"
                       placeholder="请选择分类">
              <el-option
                v-for="item in selectTopCateList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="优先级" prop="sort">
            <el-input-number v-model="productCate.sort" placeholder="添加分类描述"></el-input-number>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="productCate.description" placeholder="添加分类描述"></el-input>
          </el-form-item>
          <el-form-item label="科目" prop="subjectIds">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
            </el-checkbox>
            <el-button type="text" size="" @click="addSubject">添加科目</el-button>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="productCate.subjectIds" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="item in subjectList" :label="item.id" name="subjectIds" :key="item.id">
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>

          </el-form-item>
          <el-form-item label="是否启用：">
            <el-radio-group v-model="productCate.hidden">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDialogConfirm" size="small">确 定</el-button>
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
      </span>
      </el-dialog>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15,20]"
        :current-page.sync="listQuery.pageNum"
        :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import {
  fetchList,
  deleteProductCate,
  updateShowStatus,
  getTopCategory,
  getSubject, addSubject, getCategories, createProductCate, updateProductCate, updateHidden
} from '@/api/productCate'

const initProductCate = {
  parentId: 0,
  name: '',
  sort: 0,
  hidden: 0,
  subjectIds: [],
  description: ''
}
export default {
  name: "productCateList",
  data() {
    return {
      checkAll: false,
      isIndeterminate: false,
      productCate: {
        parentId: 0,
        name: '',
        sort: 0,
        hidden: 0,
        subjectIds: [],
        description: ''
      },
      CateId: 0,
      dialogVisible: false,
      isEdit: false,
      list: null,
      total: null,
      listLoading: true,
      cate: {
        name: '',
        parentId: 0
      },
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      parentId: 0,
      childrenList: [],
      selectTopCateList: [],
      subjectList: [],
      rules: {
        name: [
          {required: true, message: '请输入分类名称', trigger: 'change'},
          {type: 'string',message:'请输入字符串',trigger: 'change'}
        ],
        description:[
          {required: true, message: '请输入描述信息', trigger:'change'},

        ]
      }
    }
  },
  created() {
    this.resetParentId();
    this.getList();
    // this.getTopCateList();
    this.getSubjectList();
  },
  watch: {
    $route(route) {
      this.resetParentId();
      this.getList();
    }
  },
  methods: {
    handleDialogConfirm() {
      if (this.isEdit) {
        updateProductCate(this.CateId, this.productCate).then(
          res => {
            this.$message.success(res.message)
            this.dialogVisible = false;
            this.getList();
          }
        )
        console.log(this.productCate, this.CateId)
      } else {
        createProductCate(this.productCate).then(
          res => {
            this.$message.success(res.message)
            this.productCate = Object.assign({}, initProductCate)
            this.dialogVisible = false;
            this.getList();
          }
        )
      }
    },
    handleStatusChange(index, row) {
      // console.log(index,row)
      updateHidden(row.id, row.hidden).then(
        res => {
          this.$message.success(res.message)
        }
      ).catch(err => {
        this.$message.error(err)
        row.hidden = row.hidden === 1 ? 0 : 1
      })
    },
    addSubject() {
      this.$prompt('', '添加科目', {
        cancelButtonText: '取消',
        confirmButtonText: '添加',
        inputErrorMessage: '不能输入为空',
        inputPattern: /\S/
      }).then(({value}) => {
        addSubject(value).then(data => {
          this.getSubjectList();
          this.$message.success("添加科目成功");
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    getSubjectList() {
      getSubject().then(res => {
        this.subjectList = res.data
      })
    },
    getTopCateList() {
      if (!(this.isEdit && this.productCate.parentId === 0)) {
        getTopCategory().then(
          data => {
            if (data.data) {
              this.selectTopCateList = data.data;
            }
            this.selectTopCateList.unshift({id: 0, name: "顶级分类"})
          }
        )
      } else {
        this.selectTopCateList = [{
          id: 0,
          name: '顶级分类'
        }]
      }
    },
    resetList() {
      if (this.$route.query.children != null) {
        this.childrenList = this.$route.query.children
        this.list = this.childrenList
      } else {
        this.childrenList = []
      }
    },
    resetParentId() {
      this.listQuery.pageNum = 1;
      if (this.$route.query.parentId != null) {
        this.parentId = this.$route.query.parentId;
      } else {
        this.parentId = 0;
      }
    },
    handleAddProductCate() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.productCate.parentId = this.parentId;
    },
    getList() {
      this.listLoading = true;

      const params = {
        parentId: this.parentId,
        ...this.listQuery
      }
      fetchList(params).then(response => {
        this.listLoading = false;
        this.list = response.data.list
        this.total = response.data.total;
      });
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleShowStatusChange(index, row) {
      let data = new URLSearchParams();
      let ids = [];
      ids.push(row.id)
      data.append('ids', ids);
      data.append('showStatus', row.showStatus);
      updateShowStatus(data).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        });
      });
    },
    handleShowNextLevel(index, row) {
      this.$router.push({path: '/pms/productCate', query: {parentId: row.id}})
    },

    handleUpdate(index, row) {
      getCategories(row.id).then(res => {
        this.isEdit = true;
        this.dialogVisible = true;
        this.productCate = res.data;
        this.CateId = row.id;
      })
    },
    handleDelete(index, row) {
      this.$confirm('是否要删除该分类', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProductCate(row.id).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          });
          this.getList();
        });
      });
    },
    handleCheckAllChange(val) {
      this.productCate.subjectIds = val ? this.subjectList.map(i => i.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.subjectList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.subjectList.length;
    },
    closeHandler() {
      if (this.isEdit) {
        this.productCate = Object.assign({}, initProductCate)
      }
    }
  },
  filters: {
    levelFilter(value) {
      if (value === 0) {
        return '一级';
      } else if (value === 1) {
        return '二级';
      } else {
        return '多级';
      }
    },
    disableNextLevel(value) {
      if (value === 0) {
        return false;
      } else {
        return true;
      }
    }
  }
}
</script>

<style scoped>

</style>
